"""Topic和消息模板编辑对话框。"""

from __future__ import annotations

from PySide6.QtWidgets import (
    QDialog,
    QDialogButtonBox,
    QLabel,
    QMessageBox,
    QTextEdit,
    QVBoxLayout,
)

from src.services.template_validator import MessageTemplateValidator, TopicTemplateValidator


class TemplateEditDialog(QDialog):
    """模板编辑对话框。"""
    
    def __init__(self, parent=None, template_type: str = "topic", initial_template: str = "") -> None:
        """初始化对话框。
        
        Args:
            parent: 父窗口
            template_type: 模板类型，"topic" 或 "message"
            initial_template: 初始模板内容
        """
        super().__init__(parent)
        self._template_type = template_type
        self._initial_template = initial_template
        
        if template_type == "topic":
            self.setWindowTitle("编辑 Topic 模板")
            self._validator = TopicTemplateValidator()
        else:
            self.setWindowTitle("编辑消息模板")
            self._validator = MessageTemplateValidator()
        
        self._setup_ui()
    
    def _setup_ui(self) -> None:
        """设置UI。"""
        layout = QVBoxLayout(self)
        layout.setSpacing(12)
        layout.setContentsMargins(16, 16, 16, 16)
        
        # 说明标签
        if self._template_type == "topic":
            help_text = (
                "Topic 模板说明：\n"
                "- 必须包含占位符：{product_key}、{device_sn}\n"
                "- 不能包含空格\n"
                "- 只允许字母、数字、斜杠、下划线、连字符、点号和占位符\n"
                "- 示例：v1/{product_key}/{device_sn}/sys/property/up"
            )
        else:
            help_text = (
                "消息模板说明：\n"
                "- 必须是有效的JSON格式\n"
                "- 必须包含占位符：{msgid}、{params}\n"
                "- {params} 会被替换为JSON对象字符串\n"
                "- 示例：{\"msgid\": \"{msgid}\", \"params\": {params}}"
            )
        
        help_label = QLabel(help_text)
        help_label.setWordWrap(True)
        help_label.setStyleSheet("color: #666; padding: 8px; background-color: #f5f5f5; border-radius: 4px;")
        layout.addWidget(help_label)
        
        # 模板输入框
        input_label = QLabel("模板内容：")
        input_label.setStyleSheet("font-weight: bold;")
        layout.addWidget(input_label)
        
        self._template_input = QTextEdit()
        self._template_input.setPlainText(self._initial_template)
        self._template_input.setMinimumHeight(120)
        self._template_input.setPlaceholderText("请输入模板内容...")
        self._template_input.setStyleSheet("""
            QTextEdit {
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-family: 'Consolas', 'Courier New', monospace;
            }
            QTextEdit:focus {
                border: 1px solid #007bff;
            }
        """)
        layout.addWidget(self._template_input)
        
        # 验证提示标签
        self._validation_label = QLabel()
        self._validation_label.setWordWrap(True)
        self._validation_label.setStyleSheet("color: #dc3545; padding: 4px;")
        self._validation_label.hide()
        layout.addWidget(self._validation_label)
        
        # 实时验证
        self._template_input.textChanged.connect(self._validate_template)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(self._on_accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
        # 初始验证
        self._validate_template()
    
    def _validate_template(self) -> None:
        """验证模板内容。"""
        template = self._template_input.toPlainText().strip()
        
        if not template:
            self._validation_label.setText("模板不能为空")
            self._validation_label.show()
            return
        
        is_valid, error_msg = self._validator.validate(template)
        
        if is_valid:
            self._validation_label.hide()
        else:
            self._validation_label.setText(f"验证失败：{error_msg}")
            self._validation_label.show()
    
    def _on_accept(self) -> None:
        """确认按钮点击事件。"""
        template = self._template_input.toPlainText().strip()
        
        if not template:
            QMessageBox.warning(self, "验证失败", "模板不能为空")
            return
        
        is_valid, error_msg = self._validator.validate(template)
        
        if not is_valid:
            QMessageBox.warning(self, "验证失败", f"模板格式不正确：\n{error_msg}")
            return
        
        self.accept()
    
    def get_template(self) -> str:
        """获取编辑后的模板内容。"""
        return self._template_input.toPlainText().strip()

